package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.apis.schedule.IScheduleClient;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.TaskTypeEnum;
import com.heima.model.schedule.dtos.Task;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.utils.common.ProtostuffUtil;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsTaskService;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.formula.functions.T;
import org.checkerframework.checker.guieffect.qual.UI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class WmNewsTaskServiceImpl implements WmNewsTaskService {

    @Autowired
    private IScheduleClient scheduleClient;


    /**
     * 添加任务
     * @param wmNews
     */
    @Override
    public void addWmNewsToTask(WmNews wmNews) {

        Task task = new Task();
        task.setTaskType(TaskTypeEnum.NEWS_SCAN_TIME.getTaskType());
        task.setPriority(TaskTypeEnum.REMOTEERROR.getPriority());
        task.setExecuteTime(wmNews.getPublishTime().getTime());

        //序列化
        WmNews taskNews = new WmNews();
        taskNews.setId(wmNews.getId());
        task.setParameters(ProtostuffUtil.serialize(taskNews));

        scheduleClient.addTask(task);
    }

    @Autowired
    private WmNewsAutoScanService wmNewsAutoScanService;

    @Scheduled(fixedRate=1000)
    @Override
    public void pollTask() {
        ResponseResult responseResult = scheduleClient.poll(TaskTypeEnum.NEWS_SCAN_TIME.getTaskType(), TaskTypeEnum.REMOTEERROR.getPriority());
        if(responseResult != null && responseResult.getCode().equals(200) && responseResult.getData() != null){
            //获取task对象
            String task_json = JSON.toJSONString(responseResult.getData());
            Task task = JSON.parseObject(task_json, Task.class);
            //获取任务的文章id
            WmNews wmNews = ProtostuffUtil.deserialize(task.getParameters(), WmNews.class);
            //审核文章
            wmNewsAutoScanService.autoScanWmNews(wmNews.getId());
        }
    }
}
